var fs = require('fs');
var express = require('express');
var mongoStore = require('connect-mongodb');
var mongoose = require('mongoose');
var util = require('util');

/**
 * 
 * Manages an Express controller and Jade views.
 * 
 * @class ViewController
 * @author jmanero
 * 
 * @requires fs
 * @requires express
 * @requires connect-mongodb
 * @requires connect-auth
 * @requires util
 * 
 * @constructor
 * @param {Server} server
 * @param {Function} callback
 * 
 */
var ViewController = function(server, callback) {
	this.server = server;
	this.callback = callback;
	viewController = this;

	fs.readFile('./Configuration/viewController.json', function(e, content) {
		if (e)
			throw e;

		viewController.config = JSON.parse(content);
		
		viewController.controller = express.createServer();
		viewController.controller.configure(function() {
			viewController.controller.set('views', __dirname + '/'
					+ viewController.config.viewPath);
			viewController.controller.use(express.bodyParser());
			viewController.controller.use(express.cookieParser());
			viewController.controller.use(express.session({
				store : new mongoStore({
					db : connection.db
				}),
				secret : viewController.config.sessionSecret,
				cookie : viewController.config.sessionCookie
			}));

		});

		if (typeof (viewController.callback) == 'function') {
			viewController.callback();
		}

		viewController.controller.listen(viewController.config.port,
				viewController.config.interface);
	});
};

/**
 * 
 * Adds a path control to the controller
 * 
 * @param {String} module
 * @throws {TypeError}
 * 
 */
ViewController.prototype.add = function(module) {
	var control = require(this.config.controllerPath + '/' + module);
	if (!control.method || !control.path || !control.callback)
		throw TypeError("ViewController.add requires properties method, path, and callback");

	this.controller[control.method](control.path, control.callback);
};

module.exports = ViewController;
